﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Fashion.Models;
using Fashion.ViewModels;
using System.Data;
using System.IO;

namespace Fashion.Controllers
{
    public class ShoppingCartController : ThemeController
    {
        FashionEntities1 FashionDB = new FashionEntities1();
        List<Product> Cart = null;
        //
        // GET: /ShoppingCart/ViewCart
        public ActionResult ViewCart()
        {
            if (Session["cart"] != null)
            {
                ///read Cart from session if exist
                Cart = (List<Product>)Session["cart"];
            }
            else
            {
                //create an empty Cart
                Cart = new List<Product>();
            }

            double total = 0;
            foreach (Product p in Cart)
            {
                total += p.subTotal; // update total price
            }

            var viewModel = new CartViewModel
            {
                Total = total,
                Products = Cart
            };
            Session["totalItems"] = Cart.Count;
            Session["cart"] = Cart;
            return View(viewModel);
        }

        //
        // GET: /ShoppingCart/Add?pid=5&quantity=3
        public ActionResult Add(int pid, int quantity = 1)
        {
            double total = 0;
            if (Session["cart"] != null)
            {
                ///read Cart from session if exist
                Cart = (List<Product>)Session["cart"];
            }
            else
            {
                //create an empty Cart
                Cart = new List<Product>();
            }

            if (pid != 0)
            {
                string size = Request["size"];
                string color = Request["color"];
                //search item in Cart
                bool Found = false;
                foreach (Product p in Cart)
                {
                    // update added product quantity if same color&size
                    if (p.ProductID == pid && p.size == size.ToLower() && p.color == color)
                    {
                        if (quantity == 1)
                            p.quantity += 1;
                        else
                            p.quantity = quantity;
                        p.subTotal = p.Price * p.quantity;
                        // get controller of product
                        string temp = (string)p.ImageList;
                        string[] temps = temp.Split('/');
                        p.control = temps[0];
                        Found = true;
                        break;
                    }
                }
                //add new to Cart
                if (Found == false)
                {
                    var product = FashionDB.Products.Single(p => p.ProductID == pid);
                    product.quantity = 1;
                    product.subTotal = product.Price;
                    product.size = size;
                    product.color = color;

                    string temp = (string)product.ImageList;
                    string[] temps = temp.Split('/');
                    product.control = temps[0];
                    Cart.Add(product);
                }

                foreach (Product p in Cart)
                {
                    total += p.subTotal; // update total price
                }

                var viewModel = new CartViewModel
                {
                    Total = total,
                    Products = Cart
                };
                Session["totalItems"] = Cart.Count;
                Session["cart"] = Cart;
                return View(viewModel);
            }

            return View();
        }

        public ActionResult Order(int pid)
        {
            string size = Request["size"];
            string color = Request["color"];
            var product = FashionDB.Products.Single(p => p.ProductID == pid);
            CartViewModel viewModel = new CartViewModel(product);

            return View(viewModel);
        }

        public ActionResult Checkout()
        {
            
            /* XQ
             * Code to test writing data to database
             * 
            Order order = new Order();
            order.OrderDate = DateTime.Today.ToUniversalTime();
            order.ShipDate = DateTime.Today.ToUniversalTime();
            order.TotalPrice = 19.0;
            order.UserID = 5;
            order.Postalcode = "12345";
            order.City = "HCM";
            order.AddressLine1 = "KNT";
            order.AddressLine2 = null;
            order.Country = "VN";
            order.CurrentStatus = "Pending";
            
            FashionDB.AddToOrders(order);
            FashionDB.SaveChanges();

            OrderDetail orderDetailModel = new OrderDetail();
            orderDetailModel.OrderID = order.OrderID;
            orderDetailModel.ColorID = 1;
            orderDetailModel.SizeID = 1;
            orderDetailModel.Quantity = 2;
            orderDetailModel.Price = 3.5;
            orderDetailModel.CouponID = 1; //XQ
            orderDetailModel.ProductID = 96;

            FashionDB.AddToOrderDetails(orderDetailModel);
            FashionDB.SaveChanges();
             * */
            
            return View();

        }

        //
        // GET: /ShoppingCart/Remove?pid=5
        public ActionResult Remove(int pid)
        {
            try
            {
                Cart = (List<Product>)Session["cart"];
                for (int i = 0; i < Cart.Count; i++)
                {
                    if (Cart[i].ProductID == pid)
                    {
                        Cart.RemoveAt(i);
                        break;
                    }
                }
                double total = 0;
                foreach (Product p in Cart)
                {
                    total += p.subTotal; // update total price
                }

                var viewModel = new CartViewModel
                {
                    Total = total,
                    Products = Cart
                };
                Session["totalItems"] = Cart.Count;
                Session["cart"] = Cart;
                return RedirectToAction("ViewCart");
            }
            catch
            {
                return RedirectToAction("ViewCart");
            }
        }

        [HttpPost]
        public ActionResult ViewCart(FormCollection form)
        {
            string productKeyword = form["ctl00$keyword"];

            return RedirectToAction("Basic", "Search", new { keyword = productKeyword });
        }

        [HttpPost]
        public ActionResult Index(HttpPostedFileBase ImageList)
        {
            if (ImageList.ContentLength > 0)
            {
                var filename = DateTime.Now.ToString("YYYY-MMM-d-HH-mm-ss") + Path.GetExtension(ImageList.FileName);
                var path = Path.Combine(Server.MapPath("~/Content/Women"), filename);
                ImageList.SaveAs(path);
            }

            return RedirectToAction("Success", "Paypal");
        }
    }
}
